#include <SDL.h>

#include "game.h"
#include "rendermanager_sdl.h"
#include "textureloader.h"
#include "config.h"

RenderManagerSDL::RenderManagerSDL() : RenderManager()
{
}

RenderManagerSDL::~RenderManagerSDL()
{
  if(screen)
    SDL_FreeSurface(m_screen);
}

bool RenderManagerSDL::load()
{
  ConfigGroup& configGroup = m_config["render"];

  int width = configGroup.readEntry("widgth", DEFAULT_WIDTH);
  int height = configGroup.readEntry("height", DEFAULT_HEIGHT);
  int depth = configGroup.readEntry("depth", DEFAULT_DEPTH);
  Uint32 flags = configGroup.readEntry("flags",DEFAULT_RENDER_FLAGS);

  m_screen=SDL_SetVideoMode(width,height,depth,flags);

  if(m_screen==NULL)
    return false;

  configGroup.writeEntry("width",m_screen->w);
  configGroup.writeEntry("height",m_screen->h);
  configGroup.writeEntry("depth",m_screen->pitch);
  configGroup.writeEntry("flags",m_screen->flags);

	return 0;
}

bool RenderManagerSDL::reload()
{
  if(m_screen)
    SDL_FreeSurface(m_screen);

  load();
}

bool RenderManagerSDL::setFullscreen(bool fullscreen)
{
  Uint32 flags = configGroup.readEntry("flags",DEFAULT_RENDER_FLAGS);
  if(fullscreen)
    flags|=SDL_FULLSCREEN;
  else
    flag &= (~SDL_FULLSCREEN);

  configGroup.writeEntry("flags",flags);

  if(fullscreen != (screen->flags | SDL_FULLSCREEN ))
    // Avoid the warning
    return SDL_WM_ToggleFullScreen(m_screen)?true:false;

  return true;
}

bool RenderManagerSDL::getFullscreen()
{
  return m_screen->flags | SDL_FULLSCREEN;
}


void RenderManagerSDL::draw()
{
  TextureLoader& tl=Game::self().getTextureLoader();

  QuadsIt quadsIt=m_quads.begin();
  TextureIt textureIt=m_textureQuads.begin();
  
  while(quadsIt!=m_quads.end() && textureIt!=m_textureQuads.end())
  { 
    if((texture=tl.getSDLTexture(*textureIt)) != NULL)
      SDL_BlitSurface(texture,NULL,m_screen,&(*quadsIt));
  }

	//Actualizamos la pantalla
	SDL_Flip(screen);

  clear();
}
